package com.websuites.esb.cluster;

import java.io.IOException;

import org.jgroups.JChannel;
import org.jgroups.Message;
import org.springframework.core.io.Resource;

import com.websuites.utils.LogUtil;

public class BroadcastingListener
{
	private String clusterName;
	private Resource configuration;
	private ProxyReceiverAdapter receiverAdapter;
	private JChannel channel;
	
	public void setConfiguration(Resource configuration)
	{
		this.configuration = configuration;
	}
	
	public void setReceiverAdapter(ProxyReceiverAdapter receiverAdapter)
	{
		this.receiverAdapter = receiverAdapter;
	}
	
	public void setClusterName(String clusterName)
	{
		this.clusterName = clusterName;
	}

	public void start()
	{
		try
		{
			this.channel = new JChannel(configuration.getInputStream());
		    this.channel.setReceiver(this.receiverAdapter);
		    this.channel.connect(this.clusterName);
		    this.receiverAdapter.setAddress(this.channel.getAddress());
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	public void destroy() 
	{           
		if (this.channel != null)
		{                  
			this.channel.close();                  
			this.channel = null;            
		    LogUtil.info("destroy cluster " + this.clusterName);
		}      
	}
	
	public void send(Message msg) 
	{
		try
		{
			this.channel.send(msg);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
}
